package com.zwh.tomcat.filter.extend;

import java.io.IOException;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * web浏览器响应头缺失安全防护过滤器
 *
 * @author zwh
 * @date 2022-9-14
 */
public class WebResponseHeadSecurityProtectFilter implements Filter {
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
        throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest)request;
        HttpServletResponse httpServletResponse = (HttpServletResponse)response;

        // 允许放通的http method
//        Set<String> allowedHttpMethods = new HashSet<>(Arrays.asList(HttpMethod.GET.name(),HttpMethod.POST.name(),
//                HttpMethod.DELETE.name(),HttpMethod.PUT.name()));
//        if (!allowedHttpMethods.contains(httpServletRequest.getMethod())) {
//            // 非法请求方法，返回403错误码
//            httpServletResponse.setStatus(HttpStatus.FORBIDDEN.value());
//            return;
//        }

        // 解决 检测到目标X-Content-Type-Options响应头缺失
        httpServletResponse.setHeader("X-Content-Type-Options", "nosniff");
        // 解决 检测到目标X-XSS-Protection响应头缺失
        httpServletResponse.setHeader("X-XSS-Protection", "1; mode=block");
        // 检测到目标Strict-Transport-Security响应头缺失
        httpServletResponse.addHeader("Strict-Transport-Security", "max-age=172800; includeSubdomains; preload");
        // 检测到目标Strict-Transport-Security响应头缺失
        httpServletResponse.setHeader("Referrer-Policy", "origin");

        // 检测到目标X-Permitted-Cross-Domain-Policies响应头缺失
        httpServletResponse.setHeader("X-Permitted-Cross-Domain-Policies", "master-only");
        // 解决 点击劫持：X-Frame-Options未配置
        httpServletResponse.addHeader("X-Frame-Options", "SAMEORIGIN");
        // Web 服务器对于 HTTP 请求的响应头中缺少 X-Download-Options
        httpServletResponse.setHeader("X-Download-Options", "noopen");
        // 解决 检测到目标Content-Security-Policy响应头缺失
        httpServletResponse.setHeader("Content-Security-Policy",
            "object-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; " +
                    "frame-ancestors 'self'; frame-src 'self'");

        filterChain.doFilter(request, response);
    }

}
